// JavaScript Document
compass={
	canvas:null,
	dir:null,
	ref:null,
	initialCanvas:function(){
		compass.canvas = document.createElement('canvas');
		var compassDiv = document.getElementById("compass");
		compassDiv.appendChild(compass.canvas);
		compass.canvas.width = 150;
		compass.canvas.height = 150;
		compass.dir=0;
		compass.ref=0;
		compass.showcompass();
		compass.updatecompass();

		//compass.canvas.style.border = "5px inset brown";
	},
	showcompass: function(){
		var context = compass.canvas.getContext('2d');
		var imageObj = new Image();
		imageObj.src = "http://www.prism.gatech.edu/~xxie37/aro/Map/compass.png";
        imageObj.onload = function() {
       		context.drawImage(imageObj, 0, 0, 150, 150 * imageObj.height / imageObj.width );
        };		

	},
	updatecompass:function(){
		 window.addEventListener('deviceorientation', function(e) {
            var direction, delta, heading;

            if (typeof e.webkitCompassHeading !== 'undefined') {
                direction = e.webkitCompassHeading;
                if (typeof window.orientation !== 'undefined') {
                    direction += window.orientation;
                }
            } else {
                // http://dev.w3.org/geo/api/spec-source-orientation.html#deviceorientation
                direction = 360 - e.alpha;
            }

            delta = Math.round(direction) - compass.ref;
            compass.ref = Math.round(direction);
            if (delta < -180)
                delta += 360;
            if (delta > 180)
                delta -= 360;
            compass.dir += delta;

            heading = direction;
            while (heading >= 360) {
                heading -= 360;
            }
            while (heading < 0) {
                heading += 360;
            }
            heading = Math.round(heading);
            //console.log(heading);
			var angle = -compass.dir;
            document.getElementById('compass').style.webkitTransform = 'rotate(' + angle + 'deg)';
        });
	},
	clearcompass:function(){
		var context = compass.canvas.getContext('2d');
		context.clearRect ( 0 , 0 , 100 , 100 );
		compass.canvas.style.border = "none";
	},
};// JavaScript Document